package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.BusinessManagerRdbService;
import com.ndp.fb.rdb.api.FbUserRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.BusinessManager;
import com.ndp.fb.rdb.model.FbUser;
import com.ndp.fb.redis.api.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by infi on 2015/1/29.
 */
@Service
public class BusinessManagerRdbServicesImpl extends DaoTemplate implements BusinessManagerRdbService {
    @Autowired
    private FbUserRdbService fbUserRdbService;
    @Autowired
    private RedisClient redisClient;

    @Override
    public List<BusinessManager> findByUserId(String userId) {
    	FbUser fbUser = fbUserRdbService.getFbUserByUserId(userId);
    	if(fbUser==null){
    		return null;
    	}
        String sql = "select * from business_manager where fb_businesses_id in (select fb_business_id from fb_user_business_manager where fb_user_id = ?)";
        return getJdbcTemplate().query(sql, new Object[]{fbUser.getFbUserId()}, DefaultRowMapper.autoRowMapper(BusinessManager.class));
    }


    @Override
    public BusinessManager findByFbBusinessesId(Long fbBusinessesId) {
        return (BusinessManager) findOneByProperty("fb_businesses_id", fbBusinessesId.toString(),DefaultRowMapper.autoRowMapper(BusinessManager.class));
    }
    
    @Override
    public Long saveBusinessManager(final BusinessManager businessManager) {
    	String key = "BUSINESSMANAGER"+businessManager.getFbBusinessesId();
    	if(!redisClient.setNx(key, businessManager)){
    		return 0L;
    	}
    	try {
    		redisClient.expire(key, 5, TimeUnit.SECONDS.name());
    		BusinessManager businessManager1 = this.findByFbBusinessesId(businessManager.getFbBusinessesId());
        	if(businessManager1!=null){
        		return businessManager1.getId();
        	}
            return saveResultId(businessManager);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			redisClient.delete(key);
		}
    	return 0L;
    }


	@Override
	public List<BusinessManager> findByUserId(String userId, String role) {
		FbUser fbUser = fbUserRdbService.getFbUserByUserId(userId);
    	if(fbUser==null){
    		return null;
    	}
        String sql = "select * from business_manager where fb_businesses_id in (select fb_business_id from fb_user_business_manager where fb_user_id = ? and role = ? and status = 'ACTIVE')";
        return getJdbcTemplate().query(sql, new Object[]{fbUser.getFbUserId(),role}, DefaultRowMapper.autoRowMapper(BusinessManager.class));
	}
}
